/**
 * 主进程文件 执行目录是根目录跟public同一个目录
 */

'use strict'

import path from 'path'
import { app, protocol, BrowserWindow, session, ipcMain } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
// pack json
import pkg from './../../package.json'
import initIpcEvent from './modules/ipcEvent'

// 是否是开发模式
const isDevelopment = process.env.NODE_ENV === 'development'
// 是否是生产模式
const isProduction = process.env.NODE_ENV === 'production'

// 引用图标文件
const previewIcon = isDevelopment ? 'public/images/tray.ico' : './images/tray.ico'
// 上一首
const prevIcon = isDevelopment ? 'public/images/prev.png' : './images/prev.png'
// 下一首
const nextIcon = isDevelopment ? 'public/images/next.png' : './images/next.png'
// 播放
const playIcon = isDevelopment ? 'public/images/play.png' : './images/play.png'
// 暂停
const pauseIcon = isDevelopment ? 'public/images/pause.png' : './images/pause.pnng'

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow

// Scheme must be registered before the app is read
// 注册App协议
protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } }
])

// 设置底部任务栏按钮和缩略图
function setThumbarButtons (mainWindow, playing) {
  // 将指定的一组按钮添加到菜单栏的缩图工具栏上。 返回一个 Boolean 对象表示是否成功地添加了缩略图.
  // 由于空间有限, 缩图工具栏中的按钮数量不要超过7个。 一旦设置了缩略图工具栏，则无法删除。 但你可以通过调用 API 传递一个空数组来清除按钮.
  mainWindow.setThumbarButtons([
    {
      tooltip: '上一曲',
      icon: prevIcon,
      click () {
        mainWindow.webContents.send('prev-play')
      }
    },
    {
      tooltip: playing ? '暂停' : '播放',
      icon: playing ? pauseIcon : playIcon,
      click () {
        mainWindow.webContents.send('toggle-play', {
          value: !playing
        })
      }
    },
    {
      tooltip: '下一曲',
      icon: nextIcon,
      click () {
        mainWindow.webContents.send('next-play')
      }
    }
  ])
}

// 创建窗口
function createWindow () {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 1000,
    height: 690,
    minWidth: 1000,
    minHeight: 690,
    title: '网易云音乐',
    // 图标
    icon: previewIcon,
    webPreferences: {
      // Use pluginOptions.nodeIntegration, leave this alone
      // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
      // 运行Node
      nodeIntegration: true,
      // 是否允许允许Worker
      nodeIntegrationInWorker: true,
      // 网络安全
      webSecurity: false,
      // 被拖拽进入 是否打开文件
      navigateOnDragDrop: true,
      // 是否开启开发者工具
      DevTools: true
    }
  })
  // 打开开发者工具
  mainWindow.webContents.openDevTools()

  // 赋值全局属性 主窗口
  global.mainWindow = mainWindow

  // 如果是开发模式 存在开发的url
  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    mainWindow.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
    if (!process.env.IS_TEST) mainWindow.webContents.openDevTools()
  } else {
    // 注册app协议
    createProtocol('app')
    // Load the index.html when not in development
    mainWindow.loadURL('app://./index.html')
  }

  // 初始化进程之间的监听
  initIpcEvent()

  // 关闭
  mainWindow.on('closed', () => {
    mainWindow = null
  })
}

// 设置appId才能使用Notification
// 如果平台是window
if (process.platform === 'win32') {
  app.setAppUserModelId(pkg.appId)
}

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (mainWindow === null) {
    createWindow()
  }
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {
  // 加载插件
  if (process.env.NODE_ENV === 'development') {
    // 6.0的：安装vue-devtools
    BrowserWindow.addDevToolsExtension(path.resolve(__dirname, './../../devTools/vue-devtools'))
    // try {
    //   // 自己解压的插件会又key不一的控制台警告，是因为谷歌升级了安全策略 不需要管它 把开发者工具再打开就能看到vue扩展
    //   // https://github.com/electron/electron/issues/23662
    //   await session.defaultSession.loadExtension(path.resolve(__dirname, './../../devTools/vue-devtools'))
    // } catch (error) {
    //   console.log(error)
    // }
  }
  // 创建窗口
  createWindow()

  // 监听['播放'、’暂停‘]事件 设置底部任务栏
  ipcMain.on('thumbar-buttons', (e, data) => {
    if (global.mainWindow === null || mainWindow === null) return
    if (process.platform === 'win32') {
      let { playing } = data
      // 设置底部按钮
      setThumbarButtons(mainWindow, playing)
    }
  })
})

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', data => {
      if (data === 'graceful-exit') {
        app.quit()
      }
    })
  } else {
    process.on('SIGTERM', () => {
      app.quit()
    })
  }
}
